package com.atguigu.distributed.lock.zookeeper.service;

import com.atguigu.distributed.lock.redis.lock.DistributedRedisLock;
import com.atguigu.distributed.lock.zookeeper.ZkClient;
import com.atguigu.distributed.lock.zookeeper.lock.ZkDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


/**
 * @author linjy on 2022/10/10
 */
@Service
public class ZookeeperStockService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ZkClient client;

    /**
     * zookeeper分布式锁基本实现(独占排他、自旋锁：znode节点不可重复)
     */
    public void deduct1() {
        // 加锁，获取锁失败重试
        ZkDistributedLock lock = this.client.getZkDistributedLock("lock");
        lock.lock();

        // 1. 查询库存信息
        String stock = stringRedisTemplate.opsForValue().get("stock").toString();

        // 2. 判断库存是否充足
        if (stock != null && stock.length() != 0) {
            Integer st = Integer.valueOf(stock);
            if (st > 0) {
                // 3.扣减库存
                stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
            }
        }

        // 释放锁
        lock.unlock();
    }

    /**
     * 测试可重入锁
     */
    public void test(){
        ZkDistributedLock lock = this.client.getZkDistributedLock("lock");
        lock.lock();
        System.out.println("测试可重入锁");
        lock.unlock();
    }

}
